//
//  DigitalClockViewController.m
//  DigitalClock
//
//  Created by Kishikawa Katsumi on 09/10/22.
//  Copyright Kishikawa Katsumi 2009. All rights reserved.
//

#import "DigitalClockViewController.h"
#import "ClockView.h"
#import "CalendarView.h"

@interface DigitalClockViewController(Private)
- (void)buildCalendarWithDate:(NSDate *)d forPage:(NSUInteger)page;
@end

@implementation DigitalClockViewController

@synthesize twentyFourHourTime;
@synthesize flashTimeSeparator;

@synthesize weekStartsMonday;
@synthesize highlightHolidays;
@synthesize numberOfCalendarPages;

@synthesize calendar;
@synthesize now;

- (void)dealloc {
    [timer invalidate];
    [calendar release];
    [now release];
    [super dealloc];
}

- (void)loadView {
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
    self.view = contentView;
    [contentView release];
    
    UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
    [contentView addSubview:background];
    [background release];
    
    // Set up clock view
    clockView = [[ClockView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 200.0f)];
    clockView.twentyFourHourTime = twentyFourHourTime;
    clockView.flashTimeSeparator = flashTimeSeparator;
    [contentView addSubview:clockView];
    [clockView release];
    
    // Set up scroll view
    calendarScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 200.0f, 320.0f, 280.0f)];
    calendarScrollView.delegate = self;
    calendarScrollView.showsVerticalScrollIndicator = NO;
    calendarScrollView.showsHorizontalScrollIndicator = NO;
    calendarScrollView.pagingEnabled = YES;
    calendarScrollView.contentSize = CGSizeMake(320.0f * numberOfCalendarPages, 244.0f);
    [contentView addSubview:calendarScrollView];
    [calendarScrollView release];
    
    // Set up page coltrol
    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0.0f, 444.0f, 320.0f, 36.0f)];
    pageControl.numberOfPages = numberOfCalendarPages;
    [pageControl addTarget:self action:@selector(changeCalendarPage:) forControlEvents:UIControlEventValueChanged];
    [contentView addSubview:pageControl];
    [pageControl release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Set up utility objects
    self.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
    [calendarScrollView scrollRectToVisible:
     CGRectMake(calendarScrollView.frame.size.width, 0.0f, calendarScrollView.frame.size.width, calendarScrollView.frame.size.height) 
                                   animated:NO];
    pageControl.currentPage = 1;
    
    // Set up calendar views
    self.now = [NSDate date];
    NSDateComponents *components = [calendar components:(NSDayCalendarUnit | 
                                                         NSMonthCalendarUnit | 
                                                         NSYearCalendarUnit) 
                                               fromDate:now];
	[components setDay:1];
    NSInteger month = [components month];
    for (NSInteger page = 0; page < numberOfCalendarPages; page++) {
        [components setMonth:month + (page - 1)];
        
        NSDate *date = [calendar dateFromComponents:components];
        CalendarView *calendarView = [[CalendarView alloc] initWithFrame:
                        CGRectMake(calendarScrollView.frame.size.width * page, 
                                   0.0f, 
                                   calendarScrollView.frame.size.width, 
                                   calendarScrollView.frame.size.height)];
        calendarView.baseDate = date;
        calendarView.weekStartsMonday = weekStartsMonday;
        calendarView.highlightHolidays = highlightHolidays;
        [calendarScrollView addSubview:calendarView];
        [calendarView release];
    }
    
    timer = [NSTimer timerWithTimeInterval:1.0f 
                                    target:self 
                                  selector:@selector(onTimer:) 
                                  userInfo:nil 
                                   repeats:YES];
	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)onTimer:(NSTimer *)theTimer {
    [clockView update];
    
    NSDateComponents *components1 = [calendar components:(NSDayCalendarUnit | 
                                                         NSMonthCalendarUnit | 
                                                         NSYearCalendarUnit) 
                                                fromDate:now];
    NSDate *newDate = [NSDate date];
    NSDateComponents *components2 = [calendar components:(NSDayCalendarUnit | 
                                                          NSMonthCalendarUnit | 
                                                          NSYearCalendarUnit) 
                                                fromDate:newDate];
    if ([components1 day] != [components2 day]) {
        self.now = newDate;
        NSInteger month = [components2 month];
        NSArray *subviews = [calendarScrollView subviews];
        for (NSInteger page = 0; page < numberOfCalendarPages; page++) {
            CalendarView *calendarView = [subviews objectAtIndex:page];
            [components2 setMonth:month + (page - 1)];
            calendarView.baseDate = [calendar dateFromComponents:components2];
            [calendarView update];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    if (pageControlUsed) {
        return;
    }
    CGFloat pageWidth = calendarScrollView.frame.size.width;
    int page = floor((calendarScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	currentPage = page;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    pageControlUsed = NO;
    pageControl.currentPage = currentPage;
}

- (void)changeCalendarPage:(id)sender {
    NSInteger page = pageControl.currentPage;
    currentPage = page;
    
    CGRect frame = calendarScrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0.0f;
    [calendarScrollView scrollRectToVisible:frame animated:YES];
    
    pageControlUsed = YES;
}

@end
